package com.qiyang.message.emai;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * Created on 2018/7/6.
 *
 * @author sehuaqi.
 * 描述：
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String emailUsername;

    @Override
    public void sendEmail(MailInfo mailInfo) {

        if (mailInfo.isHtml()) {
            sendHtmlEmail(mailInfo);
        } else {
            sendSimpleEmail(mailInfo);
        }

    }

    private void sendSimpleEmail(MailInfo mailInfo) {
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(emailUsername);
        message.setSubject(mailInfo.getSubject());
        message.setText(mailInfo.getContent());

        for (String toAddress : mailInfo.getToAddress()) {
            message.setTo(toAddress);
            log.info("发送邮件：message = {}", message.toString());
            mailSender.send(message);
        }
    }

    public void sendHtmlEmail(MailInfo mailInfo) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message);

        try {
            messageHelper.setSubject(mailInfo.getSubject());
            messageHelper.setText(mailInfo.getContent(), true);
            messageHelper.setFrom(emailUsername);

            for (String toAddress : mailInfo.getToAddress()) {
                messageHelper.setTo(toAddress);
                log.info("发送邮件：message = {}", message.toString());
                mailSender.send(message);
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}
